﻿using AutoMapper;
using B.S.Backtrack.Domain.Entities;
using B.S.Backtrack.ErrorCode;
using B.S.Backtrack.Infrastructure.Interface;
using B.S.Backtrack.Write.API.Application.Command.Supp;
using MediatR;
using System.IO.Pipelines;

namespace B.S.Backtrack.Write.API.Application.CommandHandler.Supp
{
    public class CreateSupplierHandler : IRequestHandler<CreateSupplierCommand, ApiResult<int>>
    {
        private readonly IBaseRepository<Supplier> suRep;
        private readonly IMapper mapper;

        public CreateSupplierHandler(IBaseRepository<Supplier> suRep,IMapper mapper)
        {
            this.suRep = suRep;
            this.mapper = mapper;
        }
        public Task<ApiResult<int>> Handle(CreateSupplierCommand request, CancellationToken cancellationToken)
        {
            ApiResult<int> result = new ApiResult<int>();
            var existingRecord = suRep.GetAll().FirstOrDefault(x=>x.ProductId==request.ProductId&&x.Type==request.Type);
            if (existingRecord == null) 
            {
                // 添加新记录
                var newRecord = new Supplier
                {
                    ProductId = request.ProductId,
                    Type = request.Type,
                    ProductionBatch = request.ProductionBatch,
                    IsDel = false
                };
                suRep.Add(newRecord);
                result.Code = ApiEnums.添加成功;
                result.Msg = ApiEnums.添加成功.ToString();
                result.Data = 1;
            }
            else
            {
                // 修改现有记录
                existingRecord.ProductionBatch = request.ProductionBatch;
                suRep.Update(existingRecord);
                result.Code = ApiEnums.修改成功;
                result.Msg = ApiEnums.修改成功.ToString();
                result.Data = 1;
            }
           
            return Task.FromResult(result);
        }
    }
}
